import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/values/settings.dart';
import 'package:webview_flutter/webview_flutter.dart';

import 'index.dart';

class UserAgreeController extends GetxController {
  UserAgreeController();

  final state = UserAgreeState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();

    state.webViewController = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageFinished: (String url) {
            state.finished.value = true;
          },
          onWebResourceError: (WebResourceError error) {
            state.error.value = true;
            state.errorMsg.value = '加载失败，请稍候再试';
          },
        ),
      )
      ..loadRequest(Uri.parse(AppSettings.userAgreeLink));
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// 页面回退
  handleBack() async {
    if (await state.webViewController.canGoBack()) {
      state.webViewController.goBack();
    } else {
      Get.back();
    }
  }

  /// 重新加载
  handleReload() {
    state.webViewController.reload();
    state.finished.value = false;
    state.error.value = false;
  }
}
